import { useEffect, useState } from "react";
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { EditorState, convertToRaw, ContentState } from "draft-js";
import htmlToDraft from "html-to-draftjs";
import draftToHtml from "draftjs-to-html";
import styles from "./index.module.scss";
import { myBlockRenderer } from "../customBlockRenderFunc";

export default function InfoEditor(props: any) {
  useEffect(() => {
    // console.log(props.content);
    // html=>draft
    const html = props.content;
    if (html === undefined) return;
    const contentBlock = htmlToDraft(html);

    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(
        contentBlock.contentBlocks
      );
      const editorState = EditorState.createWithContent(contentState);
      setEditorState(editorState);
    }
  }, [props.content]);

  const [editorState, setEditorState]: any = useState("");

  return (
    <div>
      <Editor
        editorState={editorState}
        toolbarClassName={styles.toolbar}
        wrapperClassName={styles.wrapper}
        editorClassName={styles.editor}
        customBlockRenderFunc={myBlockRenderer}
        onEditorStateChange={(editorState: any) => {
          setEditorState(editorState);
        }}
        onBlur={() => {
          console.log(
            draftToHtml(convertToRaw(editorState.getCurrentContent()))
          );

          props.getContent(
            draftToHtml(convertToRaw(editorState.getCurrentContent()))
          );
        }}
        toolbar={{
          previewImage: true,
          defaultSize: {
            height: "auto",
            width: "auto",
          },
          options: [
            "inline",
            "blockType",
            "fontSize",
            "fontFamily",
            "list",
            "textAlign",
            "colorPicker",
            "link",
            "embedded",
            "image",
            "remove",
            "history",
          ],
          fontFamily: {
            options: [
              "宋体",
              "黑体",
              "楷体",
              "微软雅黑",
              "Arial",
              "Georgia",
              "Impact",
              "Tahoma",
              "Times New Roman",
              "Verdana",
            ],
          },
        }}
      />
    </div>
  );
}
